<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>欢迎登录</h1>
        <p>探索世界，发现美好</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名/邮箱/手机号"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <!-- 钉钉登录分隔线 -->
        <div class="divider">
          <span>或</span>
        </div>
        
        <!-- 钉钉登录按钮 -->
        <el-form-item>
          <el-button
            type="success"
            size="large"
            :loading="dingTalkLoading"
            class="dingtalk-button"
            @click="handleDingTalkLogin"
          >
            <span class="dingtalk-icon">🔵</span>
            {{ dingTalkLoading ? '跳转中...' : '钉钉登录' }}
          </el-button>
        </el-form-item>
        
        <div class="login-footer">
          <el-link type="primary" :underline="false" @click="showRegister = true">
            还没有账号？立即注册
          </el-link>
        </div>
      </el-form>
    </div>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegister"
      title="用户注册"
      width="400px"
      @close="resetRegisterForm"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱（可选）" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号（可选）" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="registerLoading" @click="handleRegister">
            注册
          </el-button>
          <el-button @click="showRegister = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '../api/index.js'

const router = useRouter()

const loginFormRef = ref(null)
const registerFormRef = ref(null)
const loading = ref(false)
const registerLoading = ref(false)
const dingTalkLoading = ref(false)
const showRegister = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名/邮箱/手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await authAPI.login(loginForm)
        
        if (response.access_token) {
          localStorage.setItem('token', response.access_token)
          localStorage.setItem('userInfo', JSON.stringify(response.user_info || {}))
          ElMessage.success('登录成功')
          
          // 跳转到首页
          router.push('/home')
        } else {
          ElMessage.error(response.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      try {
        const { confirmPassword, ...registerData } = registerForm
        const response = await authAPI.register(registerData)
        
        if (response.code === 200) {
          ElMessage.success('注册成功，请登录')
          showRegister.value = false
          resetRegisterForm()
        } else {
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '注册失败')
      } finally {
        registerLoading.value = false
      }
    }
  })
}

const resetRegisterForm = () => {
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
  Object.assign(registerForm, {
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    phone: ''
  })
}

// 钉钉登录处理
const handleDingTalkLogin = async () => {
  dingTalkLoading.value = true
  try {
    const response = await authAPI.getDingTalkLoginUrl()
    console.log('钉钉登录URL响应:', response)
    
    // 根据后端Response模型结构处理
    if (response.code === 200 && response.data && response.data.login_url) {
      // 跳转到钉钉登录页面
      window.location.href = response.data.login_url
    } else {
      ElMessage.error(response.message || '获取钉钉登录地址失败')
      dingTalkLoading.value = false
    }
  } catch (error) {
    console.error('获取钉钉登录URL错误:', error)
    const errorMsg = error.response?.data?.detail || error.response?.data?.message || error.message || '获取钉钉登录地址失败'
    ElMessage.error(errorMsg)
    dingTalkLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 420px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  text-align: center;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e0e0e0;
}

.divider span {
  padding: 0 15px;
  color: #999;
  font-size: 14px;
}

.dingtalk-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background-color: #1AAD19;
  border-color: #1AAD19;
}

.dingtalk-button:hover {
  background-color: #179B16;
  border-color: #179B16;
}

.dingtalk-icon {
  margin-right: 8px;
  font-size: 18px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}
</style>
